# coding: utf-8
from django.db import models
from  django.conf import settings
from django.db.models.signals import post_delete, post_save,pre_save
from django.dispatch import receiver
import datetime
import Image,ImageDraw,ImageFont
import  os,uuid


# Create your models here.




class Tag(models.Model):
    tagname=models.CharField(max_length=50)
    addtime=models.DateTimeField(default=datetime.datetime.now())
    updatetime=models.DateTimeField(default=datetime.datetime.now())
    def __unicode__(self):
        return  self.tagname

class Category(models.Model):
    categoryname=models.CharField(max_length=50)
    addtime=models.DateTimeField(default=datetime.datetime.now())
    updatetime=models.DateTimeField(default=datetime.datetime.now())
    def __unicode__(self):
        return self.categoryname

class Article(models.Model):
    title=models.CharField(max_length=200)
    content=models.TextField()
    addtime=models.DateTimeField(default=datetime.datetime.now())
    updatetime=models.DateTimeField(default=datetime.datetime.now())
    sourceurl=models.URLField(null=True,blank=True)
    sourcename=models.CharField(max_length=50,null=True,blank=True)
    description=models.TextField(max_length=500,null=True,blank=True)
    isdelete=models.BooleanField(default=False)
    state=models.BooleanField(default=True)
    category=models.ManyToManyField(Category,blank=True)
    tag=models.ManyToManyField(Tag,blank=True)

    def save(self,*args,**kwargs):
        self.updatetime=datetime.datetime.now()
        super(Article,self).save(*args,**kwargs)


    def __unicode__(self):
        return self.title


class Hit(models.Model):
    article=models.ForeignKey(Article)
    addtime=models.DateTimeField(default=datetime.datetime.now())


class Comment(models.Model):
    article=models.ForeignKey(Article)
    nickname=models.CharField(max_length=50,blank=True,null=True)
    content=models.CharField(max_length=500)
    addtime=models.DateTimeField(default=datetime.datetime.now())


class BlogImage(models.Model):
    imagefile=models.ImageField(upload_to='upload')
    usetype=models.SmallIntegerField(default=1)
    addtime=models.DateTimeField(default=datetime.datetime.now())
    remark=models.TextField(max_length=200,blank=True,null=True)


    def showurl(self):
        return self.imagefile.url
    showurl.short_description='图片地址'

    def timeformate(self):
        return '{0:%Y-%m-%d %H:%M:%S}'.format(self.addtime)
    timeformate.short_description="添加时间"

    def showimg(self):
        return '<img src="%s"/>' %self.imagefile.url
    showimg.allow_tags=True
    showimg.short_description='图片'

@receiver(pre_save,sender=BlogImage)
def presave(sender,instance,**kwsargs):
    postfix=os.path.splitext(instance.imagefile.path)
    name="{0}{1}".format(uuid.uuid1(),postfix[1])
    instance.imagefile.name=name


@receiver(post_save,sender=BlogImage)
def addwatermark(sender,instance,**kwargs):
    im=Image.open(instance.imagefile)
    watermark='www.guojl.com'
    draw=ImageDraw.Draw(im)
    font=ImageFont.truetype(os.path.join(settings.MEDIA_ROOT,'fonts','heiti.ttf'),30)
    strwidth=draw.textsize(watermark,font=font)
    imgwidt=im.size
    position=(imgwidt[0]-strwidth[0],imgwidt[1]-strwidth[1])
    draw.text(position,watermark,font=font,fill=255)
    del draw
    im.save(os.path.join(settings.MEDIA_ROOT,instance.imagefile.name))


@receiver(post_delete,sender=BlogImage)
def deleteImg(sender,instance,**kwargs):
        imgpath=os.path.join(settings.MEDIA_ROOT,instance.imagefile.name)
        if os.path.isfile(imgpath):
            try:
                os.remove(imgpath)
            except :
                pass
